package com.xysq.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.rockcent.action.CallbackListener;
import com.rockcent.model.MessageBO;
import com.rockcent.model.constant.BooleanType;
import com.umeng.analytics.MobclickAgent;
import com.xysq.adapter.MessageListAdapter;
import com.xysq.lemon.R;
import com.xysq.util.ToastUtil;
import com.xysq.util.UserInfoKeeper;

import java.util.List;

import butterknife.InjectView;


public class MessageListActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, AbsListView.OnScrollListener, AdapterView.OnItemClickListener {


    private String mLoginName;
    private MessageListAdapter mAdapter;
    private boolean isProgressing = true;
    private boolean hasMoreData = false;
    private View footerView;
    private BooleanType isComment = BooleanType.FALSE;
    private int verificationId;
    private int couponModelId;

    @InjectView(R.id.lv_data)
    ListView dataLv;
    @InjectView(R.id.ibtn_back)
    ImageButton backIv;
    @InjectView(R.id.swp_refresh)
    SwipeRefreshLayout refreshSwp;
    @InjectView(R.id.tv_reloading)
    TextView reloadingTv;
    @InjectView(R.id.pro_loading)
    ProgressBar loadingProgress;
    @InjectView(R.id.tv_empty)
    TextView emptyTv;


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("站内信页");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("站内信页");
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_list);
        initFooterView();
        mAdapter = new MessageListAdapter(MessageListActivity.this);
        dataLv.setAdapter(mAdapter);
        dataLv.setOnScrollListener(this);
        dataLv.setOnItemClickListener(this);
        backIv.setOnClickListener(this);
        dataLv.removeFooterView(footerView);
        refreshSwp.setOnRefreshListener(this);
        refreshSwp.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mLoginName = UserInfoKeeper.readPhoneNumber(this);
        reloadingTv.setOnClickListener(this);
        mAdapter.clearItems();
        currentPage = 0;
        getMessageList(currentPage);

    }

    public void initFooterView() {
        footerView = getLayoutInflater().inflate(R.layout.footer_load_more, dataLv, false);
        //此处添加footerview是为了防止类型转换错误
        dataLv.addFooterView(footerView);
    }

    private void getMessageList(int page) {
        if (TextUtils.isEmpty(mLoginName)) {
            return;
        }
        appAction.queryInmessage(mLoginName, currentPage, PAGE_SIZE, "", new CallbackListener<List<MessageBO>>() {
            @Override
            public void onSuccess(List<MessageBO> data) {
                if (currentPage == 0) {
                    mAdapter.setItems(data);
                } else {
                    mAdapter.addItems(data);
                }
                if (data.size() == PAGE_SIZE) {
                    hasMoreData = true;
                    dataLv.addFooterView(footerView);
                } else {
                    hasMoreData = false;
                    dataLv.removeFooterView(footerView);
                }
                loadingProgress.setVisibility(View.GONE);
                isProgressing = false;
                reloadingTv.setVisibility(View.GONE);
                refreshSwp.setRefreshing(false);
                if (mAdapter.isEmpty()) {
                    emptyTv.setVisibility(View.VISIBLE);
                } else {
                    emptyTv.setVisibility(View.GONE);
                }
                readMessage();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(MessageListActivity.this, message);
                reloadingTv.setVisibility(View.VISIBLE);
                loadingProgress.setVisibility(View.GONE);
                emptyTv.setVisibility(View.GONE);
                isProgressing = false;
                refreshSwp.setRefreshing(false);
            }
        });
    }

    //阅读站内信
    private void readMessage() {
        appAction.readMessage(mLoginName, -1, new CallbackListener<Void>() {//-1为全部已读
            @Override
            public void onSuccess(Void data) {
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(MessageListActivity.this, message);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        if (v == backIv) {
            finish();
        }
        if (v == reloadingTv) {
            reloadingTv.setVisibility(View.GONE);
            loadingProgress.setVisibility(View.VISIBLE);
            isProgressing = true;
            currentPage = 0;
            getMessageList(currentPage);
        }
    }

    @Override
    public void onRefresh() {
        currentPage = 0;
        mAdapter.clearItems();
        if (dataLv.getFooterViewsCount() > 0) {
            dataLv.removeFooterView(footerView);
        }
        getMessageList(currentPage);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (!isProgressing && hasMoreData && scrollState == SCROLL_STATE_IDLE
                && (view.getLastVisiblePosition() >= view.getCount() - 1)) {
            currentPage++;
            getMessageList(currentPage);
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
   /*     Inmessage inmessage = (Inmessage) mAdapter.getItem(position);
        String content = inmessage.getContent();
        if (content.indexOf("orderDetail") != -1) {//跳转到订单详情
            String orderId = content.substring(content.lastIndexOf("=") + 1, content.lastIndexOf('"'));
            Intent i = new Intent(MessageListActivity.this, OrderDetailActivity.class);
            i.putExtra(OrderDetailActivity.PARAM_ORDER_ID, Integer.parseInt(orderId));
            startActivity(i);
        }
        if (content.indexOf("identityAuth") != -1) {//填写真实姓名
            if (TextUtils.isEmpty(UserInfoKeeper.readRealName(MessageListActivity.this))) {
                startActivity(new Intent(MessageListActivity.this, RealNameAuthActivity.class));
            } else {
                ToastUtil.showShort(MessageListActivity.this, "您已补充真实姓名");
            }
        }
        if (content.indexOf("viewCouponWallet") != -1) {//实物券取消发货成功，跳转到未使用券包
            startActivity(new Intent(this, UnusedCouponActivity.class));
        }
        if (content.indexOf("marketdealDetail") != -1) {//委卖委买跳转到委托详情页
            String orderId = content.substring(content.lastIndexOf("=") + 1, content.lastIndexOf('"'));
            Intent i = new Intent(this, TradeOrderDetailActivity.class);
            i.putExtra(TradeOrderDetailActivity.PARAM_ORDER_ID, orderId);
            startActivity(i);
        }
        //取消发货成功，券已过期并且支持过期退，跳到我的页面
        //注册成功，跳转到我的页面
*//*        if (content.indexOf("viewAccount") != -1 || content.indexOf("index") != -1) {
            Intent i = new Intent(this,MainActivity.class);
            i.putExtra(MainActivity.POSITION,MainActivity.POSITION_USER);
            startActivity(i);
        }   *//*
        //取消发货成功，券已过期并且支持过期退，跳到资金管理
        if (content.indexOf("index") != -1) {
            Intent i = new Intent(this, MyWalletActivity.class);
            startActivity(i);
        }
        if (content.indexOf("viewAccount") != -1) {
            Intent i = new Intent(this, MyWalletActivity.class);
            startActivity(i);
        }
        if (content.indexOf("deliveryDetail") != -1) {//自动确认收货成功，跳到申请发货成功
            verificationId = Integer.parseInt(content.substring(content.lastIndexOf("=") + 1, content.lastIndexOf('"')).trim());
            couponModelId = Integer.parseInt(content.substring(content.lastIndexOf("?") + 1, content.lastIndexOf('&')).trim().substring(8));
            Intent i = new Intent(MessageListActivity.this, ApplySuccessSendActivity.class);
            Bundle b = new Bundle();
            b.putInt(ApplySuccessSendActivity.VERIFICATION_ID, verificationId);
            b.putInt(ApplySuccessSendActivity.COUPON_MODEL_ID, couponModelId);
            i.putExtra(ApplySuccessSendActivity.BUNDLE, b);
            startActivity(i);
        }*/
    }
    @Override
    public void finish() {
        Intent intent = new Intent(this,MainTabActivity.class);
        intent.putExtra(MainTabActivity.INDEX,MainTabActivity.TAG_INDEX);
        startActivity(intent);
    }
}
